import os
import sys
import configparser
import mysql.connector
from mysql.connector import errorcode

# Database configuration
DB_CONFIG = {
    'host': 'rm-2zea4lxfy2974xc9xso.mysql.rds.aliyuncs.com',
    'port': 3306,
    'user': 'ry',
    'password': 'Qwer1111',
    'database': 'mingxiangzhu_mall'
}

# Table definitions
TABLES = {
    'pet_ai_talk': (
        "CREATE TABLE IF NOT EXISTS `pet_ai_talk` ("
        "  `对话ID` VARCHAR(36) NOT NULL,"
        "  `消息ID` VARCHAR(36) NOT NULL,"
        "  `用户ID` VARCHAR(36) NOT NULL,"
        "  `角色` ENUM('user', 'assistant') NOT NULL,"
        "  `时间戳` TIMESTAMP(3) NOT NULL,"
        "  `内容` TEXT NOT NULL,"
        "  `状态` ENUM('已发送', '已读', '失败', '待处理') NOT NULL,"
        "  `用户意图` VARCHAR(50),"
        "  `情感分析结果` ENUM('积极', '中立', '消极'),"
        "  `用户评分/反馈` SMALLINT,"
        "  `敏感内容标记` BOOLEAN DEFAULT FALSE,"
        "  PRIMARY KEY (`消息ID`)"
        ") ENGINE=InnoDB"
    ),
    'yx_store_product_alignment': (
        "CREATE TABLE IF NOT EXISTS `yx_store_product_alignment` ("
        "  `product_id` VARCHAR(20) NOT NULL,"
        "  `product_name` VARCHAR(100) NOT NULL,"
        "  `brand` VARCHAR(50) NOT NULL,"
        "  `category` ENUM('食品', '用品', '药品') NOT NULL,"
        "  `sub_category` ENUM('主粮', '零食', '玩具', '窝垫', '驱虫药', '营养膏') NOT NULL,"
        "  `target_species` JSON NOT NULL,"
        "  `target_breeds` JSON,"
        "  `weight` FLOAT,"
        "  `size` VARCHAR(50),"
        "  `ingredients` JSON,"
        "  `material` JSON,"
        "  `text_embedding` JSON NOT NULL,"
        "  `image_embedding` JSON,"
        "  `image_hash` VARCHAR(16),"
        "  `supplier_code` VARCHAR(15) NOT NULL,"
        "  `batch_number` VARCHAR(10),"
        "  `price` FLOAT NOT NULL,"
        "  `stock_status` ENUM('0', '1', '2') NOT NULL,"
        "  `source_db` VARCHAR(50) NOT NULL,"
        "  `alignment_score` FLOAT NOT NULL,"
        "  `last_aligned_time` DATETIME NOT NULL,"
        "  PRIMARY KEY (`product_id`)"
        ") ENGINE=InnoDB"
    )
}

def create_config_files():
    # Create config directory if it doesn't exist
    if not os.path.exists('config'):
        os.makedirs('config')

    # Create db_config.ini
    db_config = configparser.ConfigParser()
    db_config['DATABASE'] = {
        'host': DB_CONFIG['host'],
        'port': str(DB_CONFIG['port']),
        'user': DB_CONFIG['user'],
        'password': DB_CONFIG['password'],
        'database': DB_CONFIG['database'],
        'dialogue_table': 'pet_ai_talk',
        'product_table': 'yx_store_product',
        'alignment_table': 'yx_store_product_alignment'
    }
    
    with open('config/db_config.ini', 'w') as configfile:
        db_config.write(configfile)

    # Create model_config.ini
    model_config = configparser.ConfigParser()
    model_config['MODEL_1'] = {
        'mode': 'production',
        'host': 'api.modelprovider1.com',
        'api_key': 'your_api_key_1'
    }
    model_config['MODEL_2'] = {
        'mode': 'staging',
        'host': 'api.modelprovider2.com',
        'api_key': 'your_api_key_2'
    }
    
    with open('config/model_config.ini', 'w') as configfile:
        model_config.write(configfile)

def initialize_database():
    try:
        cnx = mysql.connector.connect(**DB_CONFIG)
        cursor = cnx.cursor()
        
        for table_name, ddl in TABLES.items():
            try:
                print(f"Creating table {table_name}...")
                cursor.execute(ddl)
            except mysql.connector.Error as err:
                if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
                    print(f"Table {table_name} already exists.")
                else:
                    print(err.msg)
        
        cursor.close()
        cnx.close()
        
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Database does not exist")
        else:
            print(err)

def main():
    # Create configuration files
    create_config_files()
    
    # Initialize database tables
    initialize_database()
    
    print("Initialization complete!")

if __name__ == '__main__':
    # Detect operating system
    if os.name == 'nt':
        print("Running on Windows")
    else:
        print("Running on Unix-based system")
    
    main()
